import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/home/Index.vue')
      },
      {
        path: '/editor/:id?',
        name: 'Editor',
        component: () => import('@/views/editor/Index.vue')
      },
      {
        path: '/notebooks',
        name: 'Notebooks',
        component: () => import('@/views/notebooks/Index.vue')
      },
      {
        path: '/tags',
        name: 'Tags',
        component: () => import('@/views/tags/Index.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 如果 store 中没有 token，但 localStorage 有，尝试恢复
  if (!userStore.token && localStorage.getItem('access_token')) {
    userStore.restoreUser()
  }
  
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
  } else if ((to.path === '/login' || to.path === '/register') && userStore.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router

